package org.budo.ip.location.service.taobao;

import org.budo.ip.location.service.api.BudoIpLocation;
import org.budo.ip.location.service.api.BudoIpLocationService;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * 使用 ip.taobao.com 的接口，通过http方式获取一个ip所在的地理位置
 * 
 * @author lmw
 */
@Slf4j
public class TaobaoIpLocationService implements BudoIpLocationService {
    private static final String API_URL = "http://ip.taobao.com/service/getIpInfo.php";

    @Override
    public BudoIpLocation seekIpLocation(String ip) {
        if (null == ip) {
            return null;
        }

        Request request = new Request();
        request.setUrl(API_URL);
        request.setParameter("ip", ip);

        Response response = request.execute();

        if (response.getStatus() > 200) {
            log.error("#34 response=" + response);
            return null;
        }

        // {"code":0,"data":{"ip":"222.209.187.167","country":"中国","area":"","region":"四川","city":"成都","county":"XX","isp":"电信","country_id":"CN","area_id":"","":"510000","city_id":"510100","county_id":"xx","isp_id":"100017"}}
        String responseBody = response.getBody();

        JSONObject jsonObject = JSON.parseObject(responseBody);

        JSONObject dataObject = jsonObject.getJSONObject("data");

        String country = dataObject.getString("country");
        String region = dataObject.getString("region");
        String city = dataObject.getString("city");

        Integer region_id = dataObject.getInteger("region_id");
        Integer city_id = dataObject.getInteger("city_id");

        TaobaoIpLocation ipLocation = new TaobaoIpLocation();
        ipLocation.setCountry(country);
        ipLocation.setProvince(region);
        ipLocation.setCity(city);
        ipLocation.setProvinceCode(region_id);
        ipLocation.setCityCode(city_id);

        return ipLocation;
    }
}